<?php
/**
 * @link https://gitee.com/toshcn/micro-hau
 * @copyright Copyright (c) 2022/4/20 micro-hau
 * @author toshcn <toshcn@foxmail.com>
 */

namespace common\components;

use yii\base\BaseObject;

/**
 * Api 接口数据统一返回格式
 * @package api\components
 */
class ApiResponse extends BaseObject
{
    const ERROR = 0;    // 请求错误
    const SUCCESS = 1;  // 请求成功

    /**
     * @var int 错误码
     * 错误码建议用下面规则
     * 0 接口错误 1 接口成功 >1为详细错误
     * 权限错误: 1000-1999
     * 资源错误: 3000-3999
     * 请求参数错误: 4000-4999
     * 服务器错误: 5000-5999
     */
    private $_errCode = 0;

    /**
     * @var string 错误码对应提示说明.
     */
    private $_message = 'success';

    /**
     * 状态码及其对应描述文本
     * @var array
     */
    private $_apiStatusesMessage = [
        0 => 'error',
        1 => 'success'
    ];

    /**
     * 设置Api 错误码
     * @param int $value 错误码
     * @param string $text 错误码描述文本
     */
    public function setErrCode($value, $text = null)
    {
        $this->_errCode = (int) $value;
        if ($text === null) {
            $this->_message = !empty($this->_apiStatusesMessage[$this->_errCode])
                ? $this->_apiStatusesMessage[$this->_errCode]
                : '';
        } else {
            $this->_message = $text;
        }
    }

    /**
     * 接口请求成功
     *
     * @param array $data 要返回的数据内容
     * @param string $text 状态码描述文本
     * @return array
     */
    public function success($data = [], $text = null)
    {
        $this->setErrCode(static::SUCCESS, $text);
        return [
            'status' => static::SUCCESS,
            'code' => static::SUCCESS,
            'message' => $this->_message,
            'data' => $data,
        ];
    }

    /**
     * 接口请求错误
     *
     * @param int $code 错误码
     * @param array $data 要返回的数据内容
     * @param string $text 错误码描述文本
     * @return array
     */
    public function error($code = 0, $text = null, $data = [])
    {
        $this->setErrCode($code, $text);
        return [
            'status' => static::ERROR,
            'code' => $this->_errCode,
            'message' => $this->_message,
            'data' => $data
        ];
    }
}
